<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html,
      body {
        height: 100%;
      }

      #container {
        width: 100%;
        height: 100%;
      }

      .amap-icon img,
      .amap-marker-content img {
        width: 25px;
        height: 34px;
      }

      .marker {
        position: absolute;
        top: -20px;
        right: -118px;
        color: #fff;
        padding: 4px 10px;
        box-shadow: 1px 1px 1px rgba(10, 10, 10, 0.2);
        white-space: nowrap;
        font-size: 12px;
        font-family: '';
        background-color: #25a5f7;
        border-radius: 3px;
      }

      .input-card {
        width: 18rem;
        z-index: 170;
      }

      .input-card .btn {
        margin-right: 0.8rem;
      }

      .input-card .btn:last-child {
        margin-right: 0;
      }

      .del {
        position: absolute;
        top: 10px;
        left: 10px;
      }
      textarea {
        position: absolute;
        top: 30px;
        left: 10px;
      }
      #xrgj {
        position: absolute;
        top: 190px;
        left: 10px;
      }
      #clearMap {
        position: absolute;
        top: 190px;
        left: 80px;
      }
    </style>
  </head>

  <body>
    <div id="container"></div>
    <button class="del">删除最后一个点</button>
    <textarea rows="10"></textarea>
    <button id="xrgj">渲染轨迹</button>
    <button id="clearMap">清空画布</button>
    <script
      type="text/javascript"
      src="https://webapi.amap.com/maps?v=2.0&key=b0a56e953ee8b514b232380406c2baca&plugin=AMap.MouseTool&plugin=AMap.RangingTool&plugin=AMap.Marker&plugin=AMap.LngLat"
    ></script>
    <script>
      var map = new AMap.Map('container', {
        viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D',
        zoom: 11, //初始化地图层级
        center: [116.397428, 39.90923], //初始化地图中心点
      });

      const del = document.querySelector('.del');

      const input = document.querySelector('textarea');
      const xrgj = document.getElementById('xrgj');
      const clearMap = document.getElementById('clearMap');

      function renderGJ() {
        const inputValue = input.value;
        clear();
        const markers = inputValue
          .split('\n')
          .map((item) => {
            if (!item) return;
            return new AMap.Marker({
              icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
              offset: new AMap.Pixel(-13, -30),
              position: new AMap.LngLat(item.split(',')[0], item.split(',')[1]),
            });
          })
          .filter((item) => item);
        map.add(markers);
        arr = markers;
        xrgjFn(markers);
      }

      map.on('click', () => {
        renderGJ();
      });

      var mouseTool = new AMap.MouseTool(map);
      let arr = [];
      let PolylineArr = [];
      let textArr = [];
      let clearMapState = false;

      del.addEventListener('click', function () {
        const p = arr.pop();
        const line = PolylineArr.pop();
        const text = textArr.pop();
        if (input.value.split('\n').length === 1) {
          setInputValue([]);
        }
        map.remove(p);
        map.remove(line);
        map.remove(text);

        setInputValue(arr);
      });

      clearMap.addEventListener('click', function () {
        clearMapState = true;

        clear();
      });

      function clear() {
        map.clearMap();
      }

      xrgj.addEventListener('click', renderGJ);

      mouseTool.on('draw', drawMarkPolyline);

      function xrgjFn(markers) {
        clearMapState = false;
        /**
         * 防止多个DOM重叠
         * **/
        // --- start ---
        map.remove(PolylineArr);
        map.remove(textArr);
        PolylineArr = [];
        textArr = [];
        // --- end ---
        for (let i = 0; i < markers.length - 1; i++) {
          const j = i + 1;
          const p1 = markers[i].getPosition();
          const p2 = markers[j].getPosition();
          const oldLine = new AMap.Polyline({
            path: [
              [p1.KL, p1.kT],
              [p2.KL, p2.kT],
            ],
            strokeWeight: 8,
            strokeOpacity: 1,
            strokeColor: 'red',
          });
          map.add(oldLine);
          PolylineArr.push(oldLine);

          const text = new AMap.Text({
            text: '',
            style: {
              'background-color': '#29b6f6',
              'border-color': '#e1f5fe',
              'font-size': '12px',
            },
          });

          text.setMap(map);
          const textPos = p1.divideBy(2).add(p2.divideBy(2));
          const distance = Math.round(p1.distance(p2));
          text.setText('两点相距' + distance + '米');
          text.setPosition(textPos);
          textArr.push(text);
        }
      }

      function drawMarkPolyline(e) {
        if (clearMapState) {
          map.add(arr);
        }
        arr.push(e.obj);
        xrgjFn(arr);
        setInputValue(arr);
      }

      function draw(type) {
        switch (type) {
          case 'marker': {
            mouseTool.marker({
              //同Marker的Option设置
              icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
              offset: new AMap.Pixel(-13, -30),
            });

            break;
          }
          default:
            break;
        }
      }

      draw('marker');

      function setInputValue(arr) {
        input.value = arr
          .map((item) => {
            return `${item.getPosition().lng},${item.getPosition().lat}`;
          })
          .join('\n');
      }
    </script>
  </body>
</html>
